<?php

namespace app\api\biz;

use app\common\biz\Biz;
use app\common\Cache;
use app\common\enum\Cache as CacheEnum;
use app\common\enum\Code;
use app\common\model\biz\SysUserToken;
use app\common\utils\Date;
use think\facade\Request;

class TokenBiz extends Biz
{
    public static function expire(): TokenBiz
    {
        $token = Cache::get(CacheEnum::TOKEN);
        if (empty($token)) {
            return self::errorByCode(Code::TokenNotFound);
        }

        $userToken = SysUserToken::where('token', $token)->findOrEmpty();
        if ($userToken->isEmpty()) {
            return self::errorByCode(Code::DataNotFound);
        }
        if (strtotime($userToken['expire_time']) <= time()) {
            return self::errorByCode(Code::TokenExpire);
        }

        return self::success();
    }

    public static function getUserId(): TokenBiz
    {
        $token = Cache::get(CacheEnum::TOKEN);
        if (empty($token)) {
            return self::errorByCode(Code::TokenNotFound);
        }
        $userToken = SysUserToken::where('token', $token)
            ->where('expire_time', '>', Date::dt())
            ->findOrEmpty();
        if ($userToken->isEmpty()) {
            return self::errorByCode(Code::TokenExpire);
        }

        return self::success($userToken->user_id);
    }

    public static function add(int $uid, string $token, int $expire = 0): TokenBiz
    {
        if (empty($uid) || empty($token)) {
            return self::errorByCode(Code::TokenNotFound);
        }

        $expireTime = time() + (empty($expire) ? SysUserToken::$expire : $expire);
        $data = [
            'user_id' => $uid,
            'token' => $token,
            'user_agent' => Request::header('user-agent'),
            'expire_time' => date('Y-m-d H:i:s', $expireTime),
        ];
        SysUserToken::create($data);
        SysUserToken::where('expire_time', '<=', Date::dt())->delete();
        return self::success($token);
    }

    public static function del(): TokenBiz
    {
        $token = Cache::get(CacheEnum::TOKEN);
        if (empty($token)) {
            return self::errorByCode(Code::TokenNotFound);
        }

        $isOk = SysUserToken::where('token', $token)->delete();
        return self::success($isOk);
    }
}